package com.example.interceptors;

import com.example.utils.JwtUtil;
import com.example.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j

public class LoginInterceptors implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
//    通过拦截器拦截请求验证jwt令牌是否有效
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)
    {
    //      令牌验证
     String token=request.getHeader("Authorization");
//     验证token
        try
        {
            log.info("测试数据请求头");
            //   从redis中获取相同的token
            ValueOperations<String,String>operations=stringRedisTemplate.opsForValue();
            String redisToken=operations.get("token");
            if(redisToken==null)
            {
                throw new RuntimeException();
            }
            Map<String ,Object> claims = JwtUtil.parseToken(token);
            log.info("验证数据{}",claims);
//        将业务数据储存到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        }catch (Exception e)
        {
            response.setStatus(401);
            //不放行
            return false;
        }

    }
//每次登录清除上次记录
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }

}
